using System;
using System.Collections.Generic;
using System.Text;

namespace Hoshimi
{
    public class CollectorGroup_ManageState : State
	{
		#region Singleton

		// Fields
		protected static CollectorGroup_ManageState instance;

		// Constructor
		protected CollectorGroup_ManageState() : base() { }

		// Methods
		public static CollectorGroup_ManageState Instance()
		{
			// Uses "Lazy initialization"
			if( instance == null ) 
				instance = new CollectorGroup_ManageState();

			return instance;
		}

		#endregion

		public override bool Play( Unit unit )
		{
			CollectorGroup myGroup = (CollectorGroup) unit;

			if (	myGroup.IsMyNeedleTakenByEnemy()	|| 
					myGroup.IsMyNeedleFullOrDead()		|| 
					myGroup.IsMyNeedleUnderNeuroControllerAttackZone()) 
			{
				// Needle full or dead
				myGroup.myStateMachine.ChangeState( CollectorGroup_ReleaseState.Instance() );
				return false;
			}

			if ( !myGroup.IsMyNeedleAssigned() )
			{
				// Needle not yet assigned
				return true;
			}

			// Try ask necessary collectors
			myGroup.TryAskFreeBots();

			// Release unnecessary collectors
			int nbCollectorsToRelease = myGroup.myChilds.Count + myGroup.myDemandInProgress - myGroup.GetOptimalNbCollectors();
			while ( nbCollectorsToRelease > 0 ) 
			{
				// First, we release empty collectors
				Bot aBot = myGroup.GetEmptyAndFarestCollector();
				if ( aBot == null ) 
				{
					// Second, we release full collectors but farest
					aBot = myGroup.GetFarestCollector();
				}

				myGroup.Remove( aBot );
				nbCollectorsToRelease--;
			}

			return true;
		}
	}
}
